(function () {
    'use strict';

    function initialize() {
        var canvas, gl;

        canvas = document.createElement('canvas');
        document.body.appendChild(canvas);
        gl = canvas.getContext("webgl");

        console.log('Version: ' + gl.getParameter(gl.SHADING_LANGUAGE_VERSION));

        var program = compileShaders(gl, ['shader-fs', 'shader-vs']);

        window.addEventListener('resize', function() { resizeCanvas(canvas, gl); } );
        resizeCanvas( canvas, gl );
    }

    function min(a, b) {
        return a < b ? a : b;
    }

    function resizeCanvas(canvas, gl) {
        var h, w;
        h = document.body.clientHeight;//(document.body.clientHeight - 8);
        w = document.body.clientWidth;//(document.body.clientWidth - 8);

        canvas.height = min(h, w * 3 / 4);
        canvas.width = min(w, h * 4 / 3);

        gl.viewport(0, 0, canvas.width, canvas.height );
        render(gl);
    }

    function render(gl) {
        gl.clearColor(0.0, 0.0, 0.0, 1.0);

        gl.clear(gl.COLOR_BUFFER_BIT);
    }

    function getShader(gl, id) {
        var script = document.getElementById(id);
        if (!script) throw new Error(id + ': shader <script> tag not found');

        var shader;
        if (script.type === 'x-shader/x-fragment') {
            shader = gl.createShader(gl.FRAGMENT_SHADER);
        } else if (script.type === 'x-shader/x-vertex') {
            shader = gl.createShader(gl.VERTEX_SHADER);
        } else {
            throw new Error(id + ': unknown shader type: ' + script.type);
        }

        gl.shaderSource(shader, script.innerText);
        gl.compileShader(shader);

        if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
            throw new Error(id + ': GLSL compiler\n' + gl.getShaderInfoLog(shader));
        }

        return shader;
    }

    function compileShaders(gl, shaders) {
        var program = gl.createProgram();

        for (var i = 0, l = shaders.length; i < l; i++) {
            gl.attachShader(program, getShader(gl, shaders[i]));
        }

        gl.linkProgram(program);

        if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
            throw new Error('GLSL linker\n' + gl.getProgramInfoLog(program));
        }

        gl.useProgram(program);

        return program;
    }

    initialize();
}());

